package com.leyou.goods.service;

import com.leyou.goods.utils.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

@Service
public class GoodsHtmlService {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 存入到本地的静态页面
     */
    public void createStaticHtml(Long spuId){

        PrintWriter printWriter=null;
        try {
            //获取thymeleaf的上下文对象
            Context context = new Context();
            //存到我们的上下文对象中
            context.setVariables(goodsService.loadData(spuId));
            //定义静态资源存放的位置
            File file = new File("D:\\syg\\SoftMgr\\Nginx\\nginx-1.8.0\\html\\item\\"+spuId+".html");
            //写入磁盘
            printWriter = new PrintWriter(file);
            //解析并存储
            templateEngine.process("item", context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(printWriter!=null){
                //关闭资源
                printWriter.close();
            }
        }
    }


    /**
     * 新建线程处理页面静态化
     */
    public void asyncExecute(Long id){
        ThreadUtils.execute(()->
                createStaticHtml(id));
    }

    /**
     * 删除静态页面
     * @param id
     */
    public void delete(Long id) {
        File file = new File("D:\\syg\\SoftMgr\\Nginx\\nginx-1.8.0\\html\\item\\"+id+".html");
        file.delete();

    }

    public static void main(String[] args) {
        File file = new File("D:\\syg\\SoftMgr\\Nginx\\nginx-1.8.0\\html\\item\\"+2+".html");
        file.delete();
    }
}
